const { think } = require('thinkjs');
const Base = require('./base.js');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;

    const model = this.model('resource_list');
    const query = this.get();

    delete query.page;
    delete query.size;

    if (query.name) {
      query['name|remark'] = ['like', `%${query.name}%`];
      delete query.name;
    }
    query.parentId = null;

    const data = await model
      .where(query)
      .order(['id DESC'])
      .page(page, size)
      .countSelect();

    for (const item of data.data) {
      item.children = await this.model('resource_list')
        .where({ parentId: item.id })
        .select();
    }

    return this.success(data);
  }

  async putAction() {
    const values = this.post();
    const id = this.post('id');
    const model = this.model('resource_list');

    if (id > 0) {
      delete values.id;
      await model.where({ id: id }).update(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '编辑文件资料',
        content: id,
        remark: values.name,
      });
    } else {
      values.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      const addId = await model.add(values);
      this.model('addLog').add({
        user_id: this.getLoginUserId(),
        title: '新增文件资料',
        content: addId,
        remark: values.name,
      });
    }
    return this.success(values);
  }

  async detailAction() {
    const id = this.get('id');
    const data = await this.model('resource_list')
      .where({ id: id })
      .find();
    return this.success(data);
  }

  async delAction() {
    const id = this.get('id');
    await this.model('resource_list')
      .where({ id: id })
      .limit(1)
      .delete();
    return this.success();
  }
};
